<script setup lang="ts">
  import { getCodeApi, loginByMobileApi } from '@/apis/user'
  import { userStore } from '@/store/userStore'
  import { ref } from 'vue'

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
  const showCountDown = ref(false)
  const formRef = ref<UniHelper.UniFormsInstance>()
  const getMobileCode = async () => {
    await formRef.value!.validateField!(['mobile'])
    const data = await getCodeApi({ mobile: formData.value.mobile, type: 'login' })
    uni.showToast({
      title: data.code.toString(),
      icon: 'success',
    })

    formData.value.code = data.code
    showCountDown.value = true
  }
  const formData = ref({
    mobile: '13230000088',
    code: '',
  })
  const isAgree = ref(false)

  // 验证表单数据的规则
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: /^1\d{10}$/, errorMessage: '手机号码格式不正确' },
      ],
    },
    code: {
      rules: [
        { required: true, errorMessage: '请输入验证码' },
        { pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' },
      ],
    },
  }

  // 提交表单数据
  const onSubmit = async () => {
    try {
      // 验证通过后会返回表单的数据
      await formRef.value!.validate!()
      if (!isAgree.value) return uni.showToast({ title: '请勾选同意用户协议', icon: 'none' })
      const res = await loginByMobileApi(formData.value)
      // 保存token
      const store = userStore()
      userStore().token = res.token
      userStore().user = res

      uni.showToast({
        title: '登录成功',
      })
      uni.switchTab({
        url: '/pages/index/index',
      })
    } catch (error) {
      console.log(error)
    }
  }
</script>

<template>
  <uni-forms class="login-form" :model="formData" ref="formRef" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        v-model="formData.code"
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text class="text-button" v-if="!showCountDown" @click="getMobileCode">获取验证码</text>
      <view class="text-button" v-else>
        <uni-countdown
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="59"
        />秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
